<script setup>
import { ref, onMounted } from 'vue';
import { useRoute, useRouter} from 'vue-router';
import { getPetDetailAPI } from '@/apis/pet.js';
import { addAdoptionApplyAPI, getAdoptionDetailAPI, editAdoptionApplyAPI } from '@/apis/adopt.js';
import { useAuthStore } from '@/stores/auth.js';
import { storeToRefs } from 'pinia';
import { ElMessage } from 'element-plus';

const userStore = useAuthStore();
const { userDetail } = storeToRefs(userStore); 
const router = useRouter();
const route = useRoute();

// 判断是否为编辑状态
const isEdit = ref(!!route.query.adoptId);
const buttonIsDisplay = ref(route.query.purpose === 'look');
// 定义表单初始模板
const initialForm = {
    petName: '',
    petBreed: '',
    petGender: '',
    petDescription: '',
    petBackground: '',
    personName: '', 
    personPhone: '',
    personEmail: '',
    personAddress: '',
    applicationText: '',
    homeDescription: '',
    experience: '',
};

const initData = async () => {
  try {
    // 获取用户信息
    await userStore.getUserDetail(); 
    // 获取宠物详情
    await getPetDetail();

    // 编辑状态：拉取已有申请数据回显
    if (isEdit.value) {
      await getAdoptDetail();
    }
  } catch (err) {
    console.error('初始化数据失败：', err);
    ElMessage.error('页面初始化失败，请重试');
  }
};

// 初始化表单
const dialogForm = ref({ ...initialForm });

// 请求宠物详情并填充表单
const getPetDetail = async () => {
  try {
    // 从路由参数获取宠物ID
    const petId = route.query.petId;
    if (!petId) {
      ElMessage.error('未获取到宠物信息');
      router.push('/'); // 无ID则返回列表页
      return;
    }
    // 向后端请求数据
    const res = await getPetDetailAPI(petId);
    // 把后端返回的宠物数据填充到表单
    const petDetail = res.data;
    dialogForm.value = {
      ...dialogForm.value, 
      // 宠物信息
      petName: petDetail.name || '',
      petBreed: petDetail.breedName || '', 
      petGender: petDetail.gender === 'MALE' ? '公' : '母', 
      petDescription: petDetail.description || '暂无描述', 
      petBackground: petDetail.story || '暂无背景介绍', 
      // 个人信息
      personName: userDetail.value?.username || '【请前往个人资料完善】',
      personPhone: userDetail.value?.phone || '【请前往个人资料完善】',
      personEmail: userDetail.value?.email || '【请前往个人资料完善】',
      personAddress: userDetail.value?.address || '【请前往个人资料完善】',
    };
  } catch (err) {
    console.error('获取宠物详情失败：', err);
    ElMessage.error('获取宠物信息失败，请重试');
  }
};

// 获取领养申请详情（编辑时回显）
const getAdoptDetail = async () => {
  try {
    const adoptId = route.query.adoptId;
    const res = await getAdoptionDetailAPI(adoptId);
    const adoptDetail = res.data;
    // 覆盖表单已有数据
    dialogForm.value = {
      ...dialogForm.value,
      applicationText: adoptDetail.applicationText || '',
      homeDescription: adoptDetail.homeDescription || '',
      experience: adoptDetail.experience || '',
    };
  } catch (err) {
    console.error('获取申请详情失败：', err);
    ElMessage.error('获取申请信息失败，请重试');
  }
};

// 关闭对话框并重置表单
const closeDialog = () => {
    if(isEdit) {
        router.push('/adopt')
    }else {
        router.push('/');
    }
    
};

// 表单校验函数
const validateForm = () => {
  // 检查个人信息是否完善
  if (dialogForm.value.personName.includes('【请前往个人资料完善】')) {
    ElMessage.error('请先前往个人资料完善姓名信息');
    return false;
  }
  if (dialogForm.value.personPhone.includes('【请前往个人资料完善】')) {
    ElMessage.error('请先前往个人资料完善手机号信息');
    return false;
  }
  if (dialogForm.value.personEmail.includes('【请前往个人资料完善】')) {
    ElMessage.error('请先前往个人资料完善邮箱信息');
    return false;
  }
  if (dialogForm.value.personAddress.includes('【请前往个人资料完善】')) {
    ElMessage.error('请先前往个人资料完善地址信息');
    return false;
  }

  // 检查字段非空
  if (!dialogForm.value.applicationText.trim()) {
    ElMessage.error('申请理由不能为空，请填写');
    return false;
  }
  if (!dialogForm.value.homeDescription.trim()) {
    ElMessage.error('家庭环境描述不能为空，请填写');
    return false;
  }
  if (!dialogForm.value.experience.trim()) {
    ElMessage.error('养宠经验不能为空，请填写');
    return false;
  }

  // 检查字段字数限制
  if (dialogForm.value.applicationText.trim().length > 200) {
    ElMessage.error('申请理由字数不能超过200字');
    return false;
  }
  if (dialogForm.value.homeDescription.trim().length > 200) {
    ElMessage.error('家庭环境描述字数不能超过200字');
    return false;
  }
  if (dialogForm.value.experience.trim().length > 200) {
    ElMessage.error('养宠经验字数不能超过200字');
    return false;
  }

  // 检查基础ID参数
  const petId = route.query.petId;
  const userId = userDetail.value?.userId;
  if (!petId) {
    ElMessage.error('未获取到宠物ID，无法提交申请');
    return false;
  }
  if (!userId) {
    ElMessage.error('未获取到用户ID，请先登录');
    return false;
  }

  return true;
};

// 申请/编辑领养
const submitAdoption = async () => {
  if (!validateForm()) return;

  try {
    const petId = route.query.petId;
    const userId = userDetail.value.userId;
    const baseParams = { petId, userId, ...dialogForm.value };

    let res;
    if (isEdit.value) {
      // 编辑：调用编辑API，携带adoptId
      baseParams.applicationId = route.query.adoptId;
      res = await editAdoptionApplyAPI(baseParams);
    } else {
      // 新增：调用新增API
      res = await addAdoptionApplyAPI(baseParams);
    }

    if (res.code === 1) {
      ElMessage.success(isEdit.value ? '编辑申请成功' : '提交申请成功');
      router.push('/adopt');
    } else {
      ElMessage.error((isEdit.value ? '编辑' : '提交') + '失败：' + (res.msg || '未知错误'));
    }
  } catch (err) {
    ElMessage.error((isEdit.value ? '编辑' : '提交') + '失败：' + (err.msg || '网络异常'));
    console.error(err);
  }
};


onMounted(() => {
    initData();
});
</script>
<template>
    <div class="dialog-content">
        <!-- 对话框头部 -->
        <div class="dialog-header">
            <strong class="dialog-title">编辑申请资料</strong>
            <button class="close-btn" @click="closeDialog">
                <img src="/icon/x.png" alt="关闭图标" width="20px" height="20px">
            </button>
        </div>

        <div class="dialog-form">
            <!-- 宠物资料 -->
            <div class="sub-title">
                <span class="sub-title-text">宠物资料</span>
            </div>
            <div class="info-container">
                <!-- 名字 -->
                <div class="info-row">
                    <div class="label">名字</div>
                    <div class="content">{{ dialogForm.petName }}</div>
                </div>

                <!-- 品种+性别行 -->
                <div class="info-row double-row">
                    <div class="info-item">
                        <div class="label">品种</div>
                        <div class="content">{{ dialogForm.petBreed }}</div>
                    </div>
                    <div class="info-item">
                        <div class="label">性别</div>
                        <div class="content">{{ dialogForm.petGender }}</div>
                    </div>
                </div>

                 <!-- 宠物描述 -->
                 <div class="info-row long">
                    <div class="label">宠物描述</div>
                    <div class="content">{{ dialogForm.petDescription }}</div>
                </div>
                <!-- 背景介绍 -->
                <div class="info-row long">
                    <div class="label">背景介绍</div>
                    <div class="content">{{ dialogForm.petBackground }}</div>
                </div>
            </div>

            <!-- 个人资料 -->
            <div class="sub-title">
                <span class="sub-title-text">个人资料</span>
            </div>
            <div class="info-container">
                <!-- 姓名 & 手机号 -->
                <div class="info-row double-row">
                    <div class="info-item">
                        <div class="label">姓名</div>
                        <div class="content">{{ dialogForm.personName }}</div>
                    </div>
                    <div class="info-item">
                        <div class="label">手机号</div>
                        <div class="content">{{ dialogForm.personPhone }}</div>
                    </div>
                </div>

                <!-- 邮箱 -->
                <div class="info-row">
                    <div class="label">邮箱</div>
                    <div class="content">{{ dialogForm.personEmail }}</div>
                </div>
                <!-- 地址 -->
                <div class="info-row">
                    <div class="label">地址</div>
                    <div class="content">
                        {{ dialogForm.personAddress }}
                    </div>
                </div>

                <!-- 申请理由 -->
                <div class="info-row long info-text-area">
                    <div class="label">申请理由</div>
                    <div class="content cont-textarea">
                        <el-input type="textarea"  v-model="dialogForm.applicationText" placeholder="不超过200字" />
                    </div>
                </div>
                <!-- 家庭环境描述 -->
                <div class="info-row long info-text-area">
                    <div class="label">家庭环境描述</div>
                    <div class="content">
                        <el-input type="textarea" v-model="dialogForm.homeDescription" placeholder="不超过200字" />
                    </div>
                </div>
                <!-- 养宠经验 -->
                <div class="info-row long info-text-area">
                    <div class="label">养宠经验</div>
                    <div class="content">
                        <el-input type="textarea" v-model="dialogForm.experience" placeholder="不超过200字" />
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 底部按钮 -->
    <div class="dialog-footer" v-if="!buttonIsDisplay">
        <el-button style="background-color: #F2F2F2;" @click="closeDialog">
            <span>取消</span>
        </el-button>
        <el-button style="background-color: #4077FB;color: #fff;" @click="submitAdoption">
            <span>提交</span>
        </el-button>
    </div>

</template>
<style scoped>
.dialog-content {
    padding: 0 24px;
}

.dialog-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 70px;
    font-size: 18px;
}

.close-btn {
    background-color: transparent;
    border: 0;
    width: 20px;
    height: 20px;
    cursor: pointer;
}

.dialog-form {
    width: 100%;
    height: 100%;
    margin-top: 10px;
}

.sub-title {
    border-left: #58A3FE 3px solid;
}

.sub-title .sub-title-text {
    margin-left: 8px;
}

.info-container {
    margin-top: 24px;
    margin-left: 70px;
    width: calc(100% - 150px);
}

/* 单行信息 */
.info-row {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    width: 677px;
}
/* 单长行 */
.long {
    width: 100%;
}
.info-text-area {
    align-items: flex-start;
}

/* 并排信息 */
.double-row {
    display: flex;
    gap: 40px;
    width: 677px;
}

.info-item {
    display: flex;
    align-items: center;
    flex: 1;
}

.label {
    width: 96px;
    text-align: right;
    color: #787980;
    margin-right: 24px;
}

.content {
    flex: 1;
    background: #FAFAFA;
    padding: 8px 12px;
    border-radius: 4px;
    min-height: 28px;
    display: flex;
    align-items: center;
}
.cont-textarea {
    align-items: flex-start;
}

.input-inner {
    margin-left: 10px;
}

.dialog-footer {
    width: 372px;
    height: 45px;
    margin: 0 auto;
    margin-top: 31px;
    margin-bottom: 10px;
}

.dialog-footer .el-button {
    width: 76px;
    height: 100%;
}

/* 输入框聚焦样式 */
.input-box.focused {
    border: 1px solid #4077FB;
}

/* 输入框占位符颜色 */
:deep(.input-inner .el-input__inner)::placeholder {
    color: #AAB1BA;
}


/* 彻底清除当前页面el-input的默认样式 */
:deep(.content .el-input) {
  /* 清空Input组件外层容器的默认样式 */
  --el-input-hover-border-color: transparent !important;
  --el-input-focus-border-color: transparent !important;
}

/* 重置Input外层包装器（新结构的关键容器） */
:deep(.content .el-input__wrapper) {
  height: 100% !important; /* 输入框外层容器填满背景框高度 */
  border: none !important;
  box-shadow: none !important;
  background-color: transparent !important;
  padding: 0 !important;
  border-radius: 0 !important;
}

/* 重置核心输入框 */
:deep(.content .el-input__inner) {
  height: 100% !important; /* 输入框本身填满外层容器 */
  line-height: 100% !important; /* 文字行高与输入框高度一致 */
  border: none !important;
  outline: none !important;
  box-shadow: none !important;
  background-color: transparent !important;
  padding: 0 !important;
  margin: 0 !important;
  height: 28px !important; /* 与.content的min-height对齐 */
  line-height: 28px !important;
  color: inherit !important; /* 继承父级文字颜色 */
}

/* 覆盖hover/focus状态的默认样式 */
:deep(.content .el-input__wrapper:hover),
:deep(.content .el-input__wrapper:focus-within) {
  border-color: transparent !important;
  box-shadow: none !important;
}

/* 清除输入框后缀图标（如清空按钮）（如需保留可删除） */
:deep(.content .el-input__suffix) {
  display: none !important;
}
/* 彻底清除textarea外层容器的所有默认样式 */
:deep(.content .el-textarea__wrapper) {
  border: none !important;
  box-shadow: none !important;
  background: transparent !important;
  padding: 0 !important;
  margin: 0 !important;
  border-radius: 0 !important;
  height: auto !important;
}

/* 清除textarea核心输入框的所有默认样式 */
:deep(.content .el-textarea__inner) {
  border: none !important;
  outline: none !important;
  box-shadow: none !important;
  background: transparent !important;
  padding: 0 !important;
  margin: 0 !important;
  height: auto !important;
  line-height: inherit !important; /* 继承父级行高 */
  font-size: inherit !important; /* 继承父级字体大小 */
  color: inherit !important; /* 继承父级文字颜色 */
  resize: none !important; /* 禁止手动拖拽调整大小 */
  overflow: auto !important; 
}

/* 清除hover/focus状态的默认样式 */
:deep(.content .el-textarea__wrapper:hover),
:deep(.content .el-textarea__wrapper:focus-within) {
  border-color: transparent !important;
  box-shadow: none !important;
}

/* 可选：隐藏滚动条（如需） */
:deep(.content .el-textarea__inner::-webkit-scrollbar) {
  display: none !important;
}
:deep(.content .el-textarea__inner) {
  -ms-overflow-style: none !important; /* IE/Edge */
  scrollbar-width: none !important; /* Firefox */
}
</style>